package com.clay.Proxy.Cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author : clay
 * @Description:
 * @Date: Create in 8:48 2021/3/17
 * @Modified By:
 */
public class ProxyFactory implements MethodInterceptor {
    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;

    }

    public ProxyFactory() {
    }

    public Object getProxyInstrance()
    {
//        1.创建一个工具类
        Enhancer enhancer = new Enhancer();
//        2.设置父类
        enhancer.setSuperclass(target.getClass());
//        3.设置回调函数
        enhancer.setCallback(this);
//        4.创建子类对象，即代理对象
        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("Cglib代理模式 ~~ 开始");
        Object returnVal = method.invoke(target, args);
        System.out.println("Cglib代理模式 ~~ 提交");
        return returnVal;
    }
}
